﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;
using frmPrincipalTestes;

namespace frmPrincipal
{
    public partial class frmCadAttendants : Form
    {
        StandardDBConnection standardDBConnection = new StandardDBConnection();
        bool isInclusion;

        public frmCadAttendants()
        {
            InitializeComponent();
        }

        private void frmCadAtentendes_Close(object sender, EventArgs e)
        {
            standardDBConnection.cnn.Close();
            standardDBConnection.cnn.Dispose();
        }

        //Funções Auxiliares
        private void CleanFieldsData()
        {
            txtNome.Text = "";
        }
        private void CleanFields()
        {
            CleanFieldsData();
            btnDelete.Enabled = false;
            txtCodigo.Text = "";
            txtSearchByCode.Text = "";
            txtSearchByCode.Focus();
        }
        private bool IsFieldsFilled()
        {
            bool bPreenchido = true;

            if (txtNome.Text.Trim() == "")
            {
                txtNome.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtNome.BackColor = Color.White;

            return bPreenchido;
        }

        //Pesquisa Attendants
        private void SearchAttendant()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;

            string sqlCommandText, sequenceLastValueString;
            int sequenceLastValue;

            //Valida o código a ser pesquisado
            if (!Testes.ValidCode(txtSearchByCode.Text))
            {
                MessageBox.Show("Forneça um código válido!", "Cadastro de Attendants", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else
            {
        
                this.Cursor = Cursors.WaitCursor;

                sqlCommandText = "SELECT * FROM atendente WHERE cod_atend = " + txtSearchByCode.Text;
                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.Connection = standardDBConnection.cnn;
                sqlCommand.CommandText = sqlCommandText;
                databaseDataReader = sqlCommand.ExecuteReader();

                if (!databaseDataReader.HasRows)
                {
                    isInclusion = true;

                    MessageBox.Show("Não Encontrado. Portanto será utilizado o próximo código disponível para cadastro.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    sqlCommand.CommandText = "SELECT last_value FROM atendente_cod_atend_seq ";
                    databaseDataReader = sqlCommand.ExecuteReader();
                    databaseDataReader.Read();
                    sequenceLastValueString = databaseDataReader["last_value"].ToString();
                    sequenceLastValue = Convert.ToInt32(sequenceLastValueString) + 1;
                    
                    CleanFieldsData();
                    
                    txtSearchByCode.Text = sequenceLastValue.ToString();
                    txtCodigo.Text = txtSearchByCode.Text;
                    
                    btnDelete.Enabled = false;
                }
                else
                {
                    isInclusion = false;
                    databaseDataReader.Read();
                    txtCodigo.Text = databaseDataReader["cod_atend"].ToString();
                    txtNome.Text = databaseDataReader["nome_atend"].ToString();
                    btnDelete.Enabled = true;
                }

                databaseDataReader.Close();
                databaseDataReader.Dispose();
                sqlCommand.Dispose();
                this.Cursor = Cursors.Default;
            }
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchAttendant();
        }
        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                SearchAttendant();
        }

        //Botões
        private void btnNew_Click(object sender, EventArgs e)
        {
            CleanFields();
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;

            if (!IsFieldsFilled())
            {
                MessageBox.Show("Preencha os campos destacados!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            if (isInclusion)
            {
                sqlCommandText = "INSERT INTO atendente(nome_atend)";
                sqlCommandText = sqlCommandText + " values (";
                sqlCommandText = sqlCommandText + "'" + txtNome.Text + "')";
            }
            else
            {
                sqlCommandText = "update atendente ";
                sqlCommandText = sqlCommandText + "set nome_atend = '" + txtNome.Text + "'";
                sqlCommandText = sqlCommandText + " WHERE cod_atend = " + txtCodigo.Text;
            }

            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            sqlCommand.ExecuteNonQuery();

            MessageBox.Show("Gravação Efetuada com Sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            CleanFields();
            sqlCommand.Dispose();
            this.Cursor = Cursors.Default;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;
            DialogResult resp;

            resp = MessageBox.Show("Confirma a exclusão do registro?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (resp == DialogResult.Yes)
            {

                this.Cursor = Cursors.WaitCursor;

                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.Connection = standardDBConnection.cnn;
                sqlCommandText = "DELETE FROM atendente WHERE cod_atend = " + txtCodigo.Text;
                sqlCommand.CommandText = sqlCommandText;
                sqlCommand.ExecuteNonQuery();

                MessageBox.Show("Exclusão efetuada com sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                CleanFields();
                sqlCommand.Dispose();

                this.Cursor = Cursors.Default;
            }
        }

    }
}
